package be.kuleuven.peno3.mobiletoledo.Data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Class that manages settings which are stored locally.
 * 
 * @author s0213127
 *
 */
public class LocalDAO{

    private static final String KEY_PROPERTY = "property";
    private static final String KEY_VALUE = "value";
    private static final String KEY_BLOB = "blob";

    protected DatabaseHelper mDbHelper;
    protected SQLiteDatabase mDb;
    
    /**
     * Database creation sql statement
     */
    protected static final String DATABASE_NAME = "DATABASE_NAME";
    protected static final String DATABASE_TABLE = "DATABASE_TABLE";
    protected static final int DATABASE_VERSION = 11;
    protected static final String DATABASE_CREATE =
        "create table "+DATABASE_TABLE+" ("+KEY_PROPERTY+" text primary_key not null, "+KEY_VALUE+" text not null);";

    protected static final String TAG = "TAG";
    protected Context mCtx;

    protected static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public LocalDAO(Context ctx) {
        this.mCtx = ctx;
    }
    
    public LocalDAO open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    public void close() {
        mDbHelper.close();
    }
    
    public void truncate() {
    	mDb.delete(DATABASE_TABLE, null, null);
    }

    public boolean createEntry(String property, String value) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_PROPERTY, property);
        initialValues.put(KEY_VALUE, value);

        return mDb.insert(DATABASE_TABLE, null, initialValues)>0;
    }
    
    public boolean createBlob(String name, byte[] blob) {
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_PROPERTY, name);
    	initialValues.put(KEY_BLOB, blob);
    	
    	return mDb.insert(DATABASE_TABLE, null, initialValues)>0;
    }
    
    public boolean updateBlob(String name, byte[] blob) {
            ContentValues args = new ContentValues();
            args.put(KEY_BLOB, blob);

            return mDb.update(DATABASE_TABLE, args, KEY_PROPERTY + "=\'" + name + "\'", null) > 0;
        }
    
    public byte[] fetchBlob(String name) {
    	try {
        	Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_VALUE}, KEY_PROPERTY + "=" + "\'" + name + "\'", null, null, null, null, null);
			if (mCursor != null) {
			    mCursor.moveToFirst();
			}
			byte[] result=mCursor.getBlob(0);
			mCursor.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
    public String fetchProperty(String property) {
    	Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_VALUE}, KEY_PROPERTY + "=" + "\'" + property + "\'", null, null, null, null, null);
    	try {
			String result=null;
        	if (mCursor != null) {
			    mCursor.moveToFirst();
			    result=mCursor.getString(0);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			mCursor.close();
		}
    }

    /**
     * Update the entry using the details provided. The entry to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param property value to set entry property to
     * @param value to set entry value to
     * @return true if the entry was successfully updated, false otherwise
     */
    public boolean updateEntry(String property, String value) {
        ContentValues args = new ContentValues();
        args.put(KEY_VALUE, value);

        return mDb.update(DATABASE_TABLE, args, KEY_PROPERTY + "=\'" + property + "\'", null) > 0;
    }
}
